import { Component, OnInit } from '@angular/core';
import { SelectionModel } from '@angular/cdk/collections';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { MatDialog } from '@angular/material';
import { Subscription } from 'rxjs';
import { PageEvent } from '@angular/material/paginator';
import { filter } from "rxjs/operators";
import { tap } from 'rxjs/operators';

import { Department } from '../../models/Department';
import { environment } from '../../environments/environment';
import { DepartmentAddComponent } from '../departmentAdd/departmentAdd';
import { ConfirmDialogComponent } from '../confirmDialog/confirmDialog';
import { DepartmentService } from '../../service/DepartmentService';
import { AuthGuardService } from '../../service/AuthGuardService';

@Component({
  templateUrl: './departmentList.html',
  styleUrls: ['./departmentList.css']
})
export class DepartmentListComponent implements OnInit {

  selection: SelectionModel<Department>;
  cols = ['select', 'name', 'description'];
  departments: Department[];
  total: number;
  subscriptions: Subscription[] = [];
  pageSize = environment.pageSize;
  page: number = 1;
  isAdmin: boolean;

  constructor(
    private dialog: MatDialog,
    private route: ActivatedRoute,
    private router: Router,
    private departmentService: DepartmentService,
    private authGuardService: AuthGuardService,

) { }

  ngOnInit() {

   this.authGuardService.checkAdmin().subscribe((isAdmin: boolean) => {
     this.isAdmin = isAdmin;
     if (this.isAdmin) {
       this.cols = [ 'name', 'description', 'operate'];
     } else {
       this.cols = this.cols.filter(col => col  !== 'operate');
     }
   });

   this.route.data
      .subscribe((data: { results: { departments: Department[], total: number}}) => {
        this.departments = data.results.departments;
        this.total = data.results.total;
      });

    const initialSelection = [];
    const allowMultiSelect = true;
    this.selection = new SelectionModel<Department>(allowMultiSelect, initialSelection);
  }

  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.departments.length;
    return numSelected === numRows;
  }

  allToggle() {
    this.isAllSelected() ?
      this.selection.clear() :
      this.departments.forEach(row => this.selection.select(row));
  }

  onOpenAdd() {
    this.authGuardService.checkLogin().pipe(filter(res => res)).subscribe(() => {
      const dialogRef = this.dialog.open(DepartmentAddComponent, {
        width: '500px',
        height: '350px'
      });
      dialogRef.afterClosed().subscribe((result) => {
        this.update(this.page).subscribe();
      });
    });

  }

  onOpenEdit(department) {
    this.authGuardService.checkLogin().pipe(filter(res => res)).subscribe(() => {

      const dialogRef = this.dialog.open(DepartmentAddComponent, {
        width: '500px',
        height: '350px',
        data: department
      });
      dialogRef.afterClosed().subscribe((result) => {
        this.update(this.page).subscribe();
      });
    });
  }

  onDelete(id) {
    this.authGuardService.checkLogin().pipe(filter(res => res)).subscribe(() => {

      const dialogRef = this.dialog.open(ConfirmDialogComponent, {
        width: '400px',
        height: '200px',
        data: {message: '确认删除？'}
      });
      dialogRef.afterClosed().subscribe((result) => {
        if (result) {
          this.departmentService.del(id).subscribe((res) => {
            if (res.success) {
              this.update(this.page).subscribe();
            }
          });
        }
      });
    });
  }

  update(page: number = 1) {
    return this.departmentService.getDepartments(page, this.pageSize).pipe(tap((res) => {
      this.departments = res.res;
      this.total = res.total;
      this.page = page;
    }));
  }

  trackById(index: number, item: any) {
    return item.id;
  }

  onPageChanged(page: number) {
    this.page = page;
    this.update(page).subscribe();
  }
}
